﻿using System;
using Lists = Algoritmia.DataStructures.Lists;
using System.Collections.Generic;
using System.Linq;

namespace Algoritmia.Problems.CoinChange
{
    public class MoneyChangeStateSpace2 : IMoneyChangeForwardStateSpace<Tuple<int,int>,int>
    {
        private readonly int _Q;
        private readonly Lists.IList<int> _values;
        private readonly int _n;

        public MoneyChangeStateSpace2(int Q, Lists.IList<int> values)
        {
            _Q = Q;
            _values = values;
            _n = values.Count;
        }
    
        #region Implementation of IForwardStateSpace<Tuple<int,int>,int>

        public Tuple<int, int> Decide(Tuple<int, int> state, int decision)
        {
            var q = state.Item1;
            var j = _values.IndexOf(decision);
            return new Tuple<int, int>(q+decision,j);
        }

        public IEnumerable<int> Decisions(Tuple<int, int> state)
        {
            var q = state.Item1;
            var i = state.Item2;
            return from j in Enumerable.Range(i, _n - i)
                   where q + _values[j] <= _Q
                   select _values[j];
        }

        public IEnumerable<Tuple<int, int>> InitialStates
        {
            get { yield return new Tuple<int, int>(0, 0); }
        }

        public bool IsFinal(Tuple<int, int> state)
        {
            return state.Item1 == _Q;
        }

        #endregion
    }
}
